var longitude;
var latitude;
var btnid;
$.ajax({
    url: "/homepage/findTags",
    type: "POST",
    async:false,
    success: function(response) {
        $(".filters").empty()
        $(".filters").append(`<button class="filter-btn active">全部</button>`)
        for (var i = 0; i < response.data.length; i++){
            $(".filters").append(`<button class="filter-btn" id="${response.data[i].id}">${response.data[i].tagName}</button>`)
        }
    }
})
// 地图展开/收缩功能
const mapSection = document.getElementById('mapSection');
const toggleMapButton = document.getElementById('toggleMap');
const mapToggleText = document.getElementById('mapToggleText');

// 检查本地存储中的用户偏好
const isMapCollapsed = localStorage.getItem('mapCollapsed') === 'true';

// 初始化地图状态
if (isMapCollapsed) {
    mapSection.classList.add('collapsed');
    mapToggleText.textContent = '展开地图';
}

// 切换地图状态
toggleMapButton.addEventListener('click', function() {
    mapSection.classList.toggle('collapsed');

    if (mapSection.classList.contains('collapsed')) {
        mapToggleText.textContent = '展开地图';
        localStorage.setItem('mapCollapsed', 'true');
    } else {
        mapToggleText.textContent = '收起地图';
        localStorage.setItem('mapCollapsed', 'false');
    }
});

// 店铺区域展开/收缩功能
const shopsContainer = document.getElementById('shopsContainer');
const toggleShopsButton = document.getElementById('toggleShops');
const shopsToggleText = document.getElementById('shopsToggleText');
const shopsHeader = document.getElementById('shopsHeader');

// 检查本地存储中的用户偏好
const isShopsCollapsed = localStorage.getItem('shopsCollapsed') === 'true';

// 初始化店铺状态
if (isShopsCollapsed) {
    shopsContainer.classList.add('collapsed');
    shopsToggleText.textContent = '展开店铺';
}

// 切换店铺状态
toggleShopsButton.addEventListener('click', function() {
    shopsContainer.classList.toggle('collapsed');

    if (shopsContainer.classList.contains('collapsed')) {
        shopsToggleText.textContent = '展开店铺';
        localStorage.setItem('shopsCollapsed', 'true');
    } else {
        shopsToggleText.textContent = '收起店铺';
        localStorage.setItem('shopsCollapsed', 'false');
    }
});

// 点击店铺标题栏也可以切换
shopsHeader.addEventListener('click', function(e) {
    // 确保点击的不是按钮本身
    if (!e.target.closest('.toggle-shops')) {
        shopsContainer.classList.toggle('collapsed');

        if (shopsContainer.classList.contains('collapsed')) {
            shopsToggleText.textContent = '展开店铺';
            localStorage.setItem('shopsCollapsed', 'true');
        } else {
            shopsToggleText.textContent = '收起店铺';
            localStorage.setItem('shopsCollapsed', 'false');
        }
    }
});

// 模拟位置获取过程
// 位置刷新功能
document.getElementById('refreshLocation').addEventListener('click', function() {
    const locationElement = document.getElementById('locationText');
    locationElement.innerHTML = '正在重新获取位置<span class="loading-dots"></span>';

    setTimeout(() => {
        locationElement.textContent = '北京市朝阳区建国路88号';
    }, 2000);
});

// 位置分享功能
document.getElementById('shareLocation').addEventListener('click', function() {
    alert('位置分享功能已触发');
});

// 为查看详情按钮添加点击事件
document.querySelectorAll('.shop-details-btn').forEach(button => {
    button.addEventListener('click', function() {
        const shopName = this.closest('.shop-card').querySelector('.shop-title').textContent;
        alert(`即将显示${shopName}的详细信息`);
    });
});

// 筛选器按钮功能
document.querySelectorAll('.filter-btn').forEach(button => {
    button.addEventListener('click', function() {
        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        this.classList.add('active');

        // 这里可以添加实际的筛选逻辑
        const filter = this.textContent;
        const id = this.id
        btnid = id
        initEchartsChinaMap(longitude, latitude, btnid)
        // alert(`已选择筛选条件: ${filter}`);
    });
});
//
function initEchartsChinaMap() {
    // 1. 获取地图容器并初始化ECharts实例
    const chartDom = document.getElementById("shopMap");
    const myChart = echarts.init(chartDom);
    const popup = document.getElementById("shopPopup");
    const closePopupBtn = document.getElementById("closePopup");

    // 3. 从数据库获取店铺数据
    $.ajax({
        url: "recommendation/findShopById",
        type: "post",
        data:{
            id:btnid
        },
        async:false,
        success: function(response) {
            if (response.code === 200 && response.data) {
                const shopsData = response.data;

                // 处理店铺数据
                const shopPoints = shopsData.map(shop => {
                    // 处理经纬度数据
                    let longitude = shop.longitude ? parseFloat(shop.longitude) : null;
                    let latitude = shop.latitude ? parseFloat(shop.latitude) : null;

                    // 如果没有经纬度数据，使用默认坐标（北京）
                    if (!longitude || !latitude) {
                        longitude = 116.4042 + (Math.random() - 0.5) * 10;
                        latitude = 39.9153 + (Math.random() - 0.5) * 8;
                    }

                    // 处理评分数据
                    const rating = shop.rating ? parseFloat(shop.rating) : 0;

                    // 判断是否是当前位置（这里需要根据业务逻辑判断）
                    // 假设当前位置的ID为1，或者根据其他条件判断
                    const isCurrentLocation = false; // 根据实际情况修改这个条件


                    var symbolSize = 14;
                    var color = "#ff6b6b"; // 红色 - 其他位置


                    return {
                        id: shop.id,
                        name: shop.name,
                        value: [longitude, latitude],
                        rating: rating,
                        desc: shop.description || '暂无描述',
                        avatar_url: shop.avatarUrl,
                        open_time: shop.openTime || '09:00:00',
                        close_time: shop.closeTime || '18:00:00',
                        rating_count: shop.ratingCount || 0,
                        symbolSize: symbolSize,
                        itemStyle: {
                            color: color
                        },
                        isCurrentLocation: true, // 添加标记
                        label: {
                            show: isCurrentLocation || rating >= 4.0, // 当前位置和评分较高的店铺显示名称
                            formatter: function(params) {
                                return isCurrentLocation ? '当前位置' : shop.name;
                            },
                            position: 'top',
                            color: '#fff',
                            backgroundColor: isCurrentLocation ? '#4e54c8' : 'rgba(0,0,0,0.7)',
                            padding: [2, 4],
                            borderRadius: 4,
                            fontSize: 10
                        }
                    };
                });
                renderShopList(shopsData)
                // 添加当前位置到店铺数据中
                const currentLocationPoint = {
                    id: 'current_location',
                    name: '我的位置',
                    value: [longitude, latitude],
                    rating: 5,
                    desc: '当前位置',
                    avatar_url: null,
                    open_time: '全天',
                    close_time: '全天',
                    rating_count: 0,
                    symbolSize: 20,
                    itemStyle: {
                        color: "#4e54c8"
                    },
                    isCurrentLocation: false,
                    label: {
                        show: true,
                        formatter: '我的位置',
                        position: 'top',
                        color: '#fff',
                        backgroundColor: '#4e54c8',
                        padding: [4, 8],
                        borderRadius: 4,
                        fontSize: 12,
                        fontWeight: 'bold'
                    }
                };

                shopPoints.push(currentLocationPoint);
                console.log(shopPoints)


                // 4. 加载中国地图数据
                fetch('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('地图数据加载失败');
                        }
                        return response.json();
                    })
                    .then(chinaJson => {
                        // 注册地图
                        echarts.registerMap('china', chinaJson);

                        // 5. 设置ECharts配置项
                        const option = {
                            backgroundColor: "#f8f9fa",
                            title: {
                                text: `全国店铺分布 (${shopPoints.length -1}家)`,
                                left: "center",
                                textStyle: {
                                    color: "#212529",
                                    fontSize: 16,
                                    fontWeight: "600"
                                }

                            },
                            tooltip: {
                                trigger: "item",
                                backgroundColor: "rgba(255, 255, 255, 0.95)",
                                borderColor: "#e9ecef",
                                borderWidth: 1,
                                textStyle: {
                                    color: "#212529"
                                },
                                formatter: function(params) {
                                    if (params.seriesType === "scatter") {
                                        const shop = params.data;
                                        const stars = '★'.repeat(Math.floor(shop.rating)) + '☆'.repeat(5 - Math.floor(shop.rating));
                                        const locationBadge = shop.isCurrentLocation ?
                                            '<span style="background: #4e54c8; color: white; padding: 2px 6px; border-radius: 10px; font-size: 10px; margin-left: 8px;">当前位置</span>' : '';

                                        return `
                                            <div style="padding: 12px; min-width: 200px;">
                                                <div style="display: flex; align-items: center; margin-bottom: 8px;">
                                                    ${shop.avatar_url ?
                                            `<img src="${shop.avatar_url}" style="width: 40px; height: 40px; border-radius: 8px; margin-right: 8px; object-fit: cover;">` :
                                            `<div style="width: 40px; height: 40px; border-radius: 8px; margin-right: 8px; background: ${shop.isCurrentLocation ? '#4e54c8' : '#ff6b6b'}; display: flex; align-items: center; justify-content: center; color: white;">
                                                            <i class="fas fa-store"></i>
                                                        </div>`
                                        }
                                                    <div style="flex: 1;">
                                                        <div style="display: flex; align-items: center;">
                                                            <h4 style="margin: 0; color: ${shop.isCurrentLocation ? '#4e54c8' : '#ff6b6b'}; font-size: 14px;">${shop.name}</h4>
                                                            ${locationBadge}
                                                        </div>
                                                        <div style="color: #f8961e; font-size: 12px;">${stars} ${shop.rating}</div>
                                                    </div>
                                                </div>
                                                <p style="margin: 4px 0; color: #495057; font-size: 12px;">${shop.desc}</p>
                                                <p style="margin: 4px 0; color: #6c757d; font-size: 11px;">
                                                    <i class="fas fa-clock"></i> ${shop.open_time} - ${shop.close_time}
                                                </p>
                                                <p style="margin: 4px 0; color: #6c757d; font-size: 11px;">
                                                    <i class="fas fa-star"></i> ${shop.rating_count} 条评价
                                                </p>
                                            </div>
                                        `;
                                    }
                                    return params.name;
                                }
                            },
                            visualMap: {
                                show: true,
                                type: "piecewise",
                                pieces: [
                                    { min: 4.5, label: '优秀 (4.5+)', color: "#ff6b6b" },
                                    { min: 4.0, max: 4.4, label: '良好 (4.0-4.4)', color: "#4895ef" },
                                    { min: 3.0, max: 3.9, label: '一般 (3.0-3.9)', color: "#7209b7" },
                                    { max: 2.9, label: '待改善 (<3.0)', color: "#adb5bd" }
                                ],
                                left: "left",
                                top: "bottom",
                                textStyle: {
                                    color: "#495057",
                                    fontSize: 11
                                },
                                itemWidth: 12,
                                itemHeight: 12,
                                borderColor: "#e9ecef"
                            },
                            geo: {
                                map: "china",
                                roam: true,
                                center: [105.0, 36.0],
                                zoom: 1.2,
                                label: {
                                    show: true,
                                    color: "#495057",
                                    fontSize: 10,
                                    fontWeight: "normal"
                                },
                                emphasis: {
                                    label: {
                                        color: "#4361ee",
                                        fontSize: 11,
                                        fontWeight: "bold"
                                    },
                                    itemStyle: {
                                        areaColor: "#e3f2fd",
                                        borderColor: "#4361ee",
                                        borderWidth: 1
                                    }
                                },
                                itemStyle: {
                                    areaColor: "rgba(67, 97, 238, 0.05)",
                                    borderColor: "rgba(67, 97, 238, 0.3)",
                                    borderWidth: 0.5
                                }
                            },
                            series: [
                                // 当前位置标记（蓝色）
                                {
                                    id: "currentLocation",
                                    name: "当前位置",
                                    type: "scatter",
                                    coordinateSystem: "geo",
                                    zlevel: 5, // 更高层级，确保显示在最前面
                                    symbol: "circle",
                                    data: shopPoints.filter(shop => shop.isCurrentLocation),
                                    symbolSize: 20,
                                    itemStyle: {
                                        color: "#4e54c8"
                                    },
                                    emphasis: {
                                        itemStyle: {
                                            shadowBlur: 15,
                                            shadowColor: 'rgba(78, 84, 200, 0.8)',
                                            borderColor: '#4e54c8',
                                            borderWidth: 3
                                        },
                                        label: {
                                            show: true,
                                            fontWeight: 'bold',
                                            backgroundColor: '#4e54c8'
                                        }
                                    },
                                    label: {
                                        show: true,
                                        formatter: '当前位置',
                                        position: 'top',
                                        color: '#fff',
                                        backgroundColor: '#4e54c8',
                                        padding: [4, 8],
                                        borderRadius: 4,
                                        fontSize: 12,
                                        fontWeight: 'bold'
                                    }
                                },
                                // 其他店铺标记（红色）
                                {
                                    id: "otherShops",
                                    name: "其他店铺",
                                    type: "scatter",
                                    coordinateSystem: "geo",
                                    zlevel: 4,
                                    symbol: "circle",
                                    data: shopPoints.filter(shop => !shop.isCurrentLocation),
                                    symbolSize: 14,
                                    itemStyle: {
                                        color: "#ff6b6b"
                                    },
                                    emphasis: {
                                        itemStyle: {
                                            shadowBlur: 10,
                                            shadowColor: 'rgba(255, 107, 107, 0.5)',
                                            borderColor: '#ff6b6b',
                                            borderWidth: 2
                                        },
                                        label: {
                                            show: true,
                                            fontWeight: 'bold'
                                        }
                                    },
                                    label: {
                                        show: true,
                                        formatter: '{b}',
                                        position: 'top',
                                        color: '#fff',
                                        backgroundColor: 'rgba(0,0,0,0.7)',
                                        padding: [2, 4],
                                        borderRadius: 4,
                                        fontSize: 10
                                    }
                                }
                            ],
                            legend: {
                                show: true,
                                orient: 'horizontal',
                                left: 'center',
                                top: 30,
                                data: ['当前位置', '其他店铺'],
                                textStyle: {
                                    color: '#495057',
                                    fontSize: 12
                                }
                            }
                        };

                        // 6. 渲染地图
                        myChart.setOption(option);

                        // // 7. 添加点击事件处理
                        // myChart.on('click', function(params) {
                        //     if (params.seriesType === "scatter") {
                        //         const shop = params.data;
                        //         showShopPopup(shop, params.event.event);
                        //     }
                        // });

                        // 8. 添加控制功能
                        setupControls(myChart);
                    })
                    .catch(error => {
                        console.error('加载地图数据失败:', error);
                        // 可以在这里添加错误处理，比如显示错误信息
                    });
            }
        },
        error: function(xhr, status, error) {
            console.error('获取店铺数据失败:', error);
            // 可以在这里添加错误处理
        }
    });

    // 显示店铺详情弹窗
    function showShopPopup(shopData, event) {
        const popup = document.getElementById("shopPopup");

        // 更新弹窗内容
        document.getElementById("popupTitle").textContent = shopData.name;
        document.getElementById("popupRating").textContent = shopData.rating;
        document.getElementById("popupLocation").textContent = `经度: ${shopData.value[0].toFixed(4)}, 纬度: ${shopData.value[1].toFixed(4)}`;
        document.getElementById("popupType").textContent = shopData.desc || '暂无描述';

        // 设置弹窗标题颜色
        const popupTitle = document.getElementById("popupTitle");
        popupTitle.style.color = shopData.isCurrentLocation ? "#4e54c8" : "#ff6b6b";

        // 先显示弹窗以获取实际尺寸
        popup.style.display = 'block';
        popup.style.visibility = 'hidden';

        // 获取弹窗的实际尺寸
        const popupRect = popup.getBoundingClientRect();
        const popupWidth = popupRect.width;
        const popupHeight = popupRect.height;

        // 恢复可见性
        popup.style.visibility = 'visible';

        // 获取点击位置
        const clickX = event.clientX;
        const clickY = event.clientY;

        // 获取视口尺寸和滚动位置
        const windowWidth = window.innerWidth;
        const windowHeight = window.innerHeight;
        const scrollX = window.pageXOffset || document.documentElement.scrollLeft;
        const scrollY = window.pageYOffset || document.documentElement.scrollTop;

        // 计算绝对位置
        let absoluteX = clickX + scrollX;
        let absoluteY = clickY + scrollY;

        // 智能定位算法
        let finalX, finalY;

        // 水平定位策略
        const spaceRight = windowWidth - clickX - 20;
        const spaceLeft = clickX - 20;

        if (spaceRight >= popupWidth || spaceRight >= spaceLeft) {
            finalX = absoluteX + 15;
        } else {
            finalX = absoluteX - popupWidth - 15;
        }

        // 垂直定位策略
        const spaceBelow = windowHeight - clickY - 20;
        const spaceAbove = clickY - 20;

        if (spaceBelow >= popupHeight || spaceBelow >= spaceAbove) {
            finalY = absoluteY + 15;
        } else {
            finalY = absoluteY - popupHeight - 15;
        }

        // 边界检查
        finalX = Math.max(10, Math.min(finalX, scrollX + windowWidth - popupWidth - 10));
        finalY = Math.max(10, Math.min(finalY, scrollY + windowHeight - popupHeight - 10));

        // 应用位置
        popup.style.position = 'fixed';
        popup.style.left = finalX + 'px';
        popup.style.top = finalY + 'px';
        popup.style.zIndex = '10000';

        // 添加动画效果
        popup.style.opacity = '0';
        popup.style.transform = 'translateY(-10px) scale(0.95)';

        requestAnimationFrame(() => {
            popup.style.transition = 'all 0.2s cubic-bezier(0.4, 0, 0.2, 1)';
            popup.style.opacity = '1';
            popup.style.transform = 'translateY(0) scale(1)';
        });

        // 点击外部关闭
        const closeOnOutsideClick = (e) => {
            if (!popup.contains(e.target)) {
                popup.style.display = 'none';
                document.removeEventListener('click', closeOnOutsideClick);
            }
        };

        setTimeout(() => {
            document.addEventListener('click', closeOnOutsideClick);
        }, 100);
    }

    // 设置控制功能
    function setupControls(myChart) {
        window.addEventListener("resize", function() {
            myChart.resize();
        });
    }
}

// 页面加载完成后初始化地图
document.addEventListener('DOMContentLoaded', function() {
    var longitude1 = $.cookie("longitude")
    var latitude1 = $.cookie("latitude")
    // 先获取当前位置，然后初始化地图
    getAddressFromKnownCoordinates(longitude1, latitude1)
        .then(addressInfo => {
            console.log('完整地址:', addressInfo.fullAddress);
            console.log('省份:', addressInfo.province);
            console.log('城市:', addressInfo.city);
            console.log('区域:', addressInfo.district);
            longitude = longitude1
            latitude = latitude1
            $("#locationText").html(addressInfo.province+" "+addressInfo.city+" "+addressInfo.district)
            initEchartsChinaMap(longitude1, latitude1,btnid);
        })

});

// 获取当前位置的经纬度
function getCurrentLocation() {
    return new Promise((resolve, reject) => {
        // 检查浏览器是否支持Geolocation API
        if (!navigator.geolocation) {
            reject(new Error('您的浏览器不支持地理位置功能'));
            return;
        }

        // 获取当前位置
        navigator.geolocation.getCurrentPosition(
            // 成功回调
            (position) => {
                const latitude = position.coords.latitude;  // 纬度
                const longitude = position.coords.longitude; // 经度
                const accuracy = position.coords.accuracy;   // 精度（米）

                resolve({
                    latitude: latitude,
                    longitude: longitude,
                    accuracy: accuracy,
                    timestamp: position.timestamp
                });
            },
            // 错误回调
            (error) => {
                let errorMessage;
                switch(error.code) {
                    case error.PERMISSION_DENIED:
                        errorMessage = '用户拒绝提供地理位置权限';
                        break;
                    case error.POSITION_UNAVAILABLE:
                        errorMessage = '无法获取当前位置信息';
                        break;
                    case error.TIMEOUT:
                        errorMessage = '获取位置信息超时';
                        break;
                    default:
                        errorMessage = '发生未知错误';
                        break;
                }
                reject(new Error(errorMessage));
            },
            // 选项配置
            {
                enableHighAccuracy: true,    // 高精度模式
                timeout: 10000,              // 超时时间（10秒）
                maximumAge: 60000            // 缓存位置的最大年龄（60秒）
            }
        );
    });
}
function getAddressFromKnownCoordinates(longitude, latitude) {
    return new Promise((resolve, reject) => {
        const apiKey = '2105ba620f46e78a74b47d937077308a';
        const url = `https://restapi.amap.com/v3/geocode/regeo?key=${apiKey}&location=${longitude},${latitude}&output=JSON`;

        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.status === '1' && data.regeocode) {
                    const addressComponent = data.regeocode.addressComponent;
                    resolve({
                        fullAddress: data.regeocode.formatted_address,
                        province: addressComponent.province,
                        city: addressComponent.city || addressComponent.province,
                        district: addressComponent.district,
                        township: addressComponent.township,
                        street: addressComponent.streetNumber?.street || '',
                        streetNumber: addressComponent.streetNumber?.number || '',
                        citycode: addressComponent.citycode,
                        adcode: addressComponent.adcode
                    });
                } else {
                    reject(new Error('获取地址信息失败: ' + (data.info || '未知错误')));
                }
            })
            .catch(error => {
                reject(error);
            });
    });
}
// 渲染店铺列表到HTML
function renderShopList(shopsData) {
    const shopsContainer = document.getElementById('shopsContainer');

    if (!shopsData || shopsData.length === 0) {
        shopsContainer.innerHTML = `
            <div class="no-shops">
                <i class="fas fa-store-slash"></i>
                <p>暂无推荐店铺</p>
            </div>
        `;
        return;
    }

    // 更新店铺数量
    const shopsTitle = document.querySelector('.shops-title');
    if (shopsTitle) {
        shopsTitle.innerHTML = `<i class="fas fa-store"></i> 推荐店铺 (${shopsData.length})`;
    }

    const shopsHtml = shopsData.map(shop => `
        <section class="shop-card" data-shop-id="${shop.id}">
            <div class="shop-carousel">
                ${renderShopImages(JSON.parse(shop.bannerUrls))}
            </div>
            <div class="shop-content">
                <div class="shop-header">
                    <h3 class="shop-title">${shop.name || '未知店铺'}</h3>
                    <span class="shop-badge ${getBadgeClass(shop)}">${getBadgeText(shop)}</span>
                </div>
                <div class="shop-rating">
                    <span class="stars">${generateStars(shop.rating || 0)}</span>
                    <span class="rating-text">${(shop.rating || 0).toFixed(1)}</span>
                    <span class="rating-count">(${shop.ratingCount || 0}条评价)</span>
                </div>
                <p class="shop-description">${shop.desc || '暂无描述'}</p>
                <div class="shop-info">
                    <div class="info-item">
                        <i class="fas fa-clock"></i>
                        <span>${shop.openTime || '09:00'} - ${shop.closeTime || '18:00'}</span>
                    </div>
                </div>
                <button class="shop-details-btn" onclick="viewShopDetail(${shop.id})">
                    查看详情 <i class="fas fa-chevron-right"></i>
                </button>
            </div>
        </section>
    `).join('');

    shopsContainer.innerHTML = shopsHtml;

    // 初始化所有轮播图
    initializeAllCarousels();
}

// 渲染店铺图片轮播
function renderShopImages(images) {
    if (!images) {
        return `
            <div class="carousel-slide active">
                <div class="no-image">
                    <i class="fas fa-store"></i>
                    <span>暂无图片</span>
                </div>
            </div>
        `;
    }

    // 如果images是字符串，转换为数组
    const imageArray = Array.isArray(images) ? images : [images];

    if (imageArray.length === 0) {
        return `
            <div class="carousel-slide active">
                <div class="no-image">
                    <i class="fas fa-store"></i>
                    <span>暂无图片</span>
                </div>
            </div>
        `;
    }

    const slidesHtml = imageArray.map((img, index) => `
        <div class="carousel-slide ${index === 0 ? 'active' : ''}">
            <img src="${img}" alt="店铺图片" onerror="this.src=''">
        </div>
    `).join('');

    return `
        <div class="carousel-container">
            <div class="carousel-track">
                ${slidesHtml}
            </div>
            ${imageArray.length > 1 ? `
                <button class="carousel-btn carousel-prev">
                    <i class="fas fa-chevron-left"></i>
                </button>
                <button class="carousel-btn carousel-next">
                    <i class="fas fa-chevron-right"></i>
                </button>
                <div class="carousel-indicators">
                    ${imageArray.map((_, index) => `
                        <span class="indicator ${index === 0 ? 'active' : ''}"></span>
                    `).join('')}
                </div>
            ` : ''}
        </div>
    `;
}

// 初始化所有轮播图
function initializeAllCarousels() {
    document.querySelectorAll('.carousel-container').forEach(container => {
        initializeCarousel(container);
    });
}

// 初始化单个轮播图
function initializeCarousel(container) {
    const track = container.querySelector('.carousel-track');
    const slides = container.querySelectorAll('.carousel-slide');
    const prevBtn = container.querySelector('.carousel-prev');
    const nextBtn = container.querySelector('.carousel-next');
    const indicators = container.querySelectorAll('.indicator');

    if (slides.length <= 1) return;

    let currentIndex = 0;

    function updateCarousel() {
        track.style.transform = `translateX(-${currentIndex * 100}%)`;

        // 更新指示器
        indicators.forEach((indicator, index) => {
            indicator.classList.toggle('active', index === currentIndex);
        });

        // 更新幻灯片
        slides.forEach((slide, index) => {
            slide.classList.toggle('active', index === currentIndex);
        });
    }

    function nextSlide() {
        currentIndex = (currentIndex + 1) % slides.length;
        updateCarousel();
    }

    function prevSlide() {
        currentIndex = (currentIndex - 1 + slides.length) % slides.length;
        updateCarousel();
    }

    // 事件监听
    if (nextBtn) nextBtn.addEventListener('click', nextSlide);
    if (prevBtn) prevBtn.addEventListener('click', prevSlide);

    // 指示器点击
    indicators.forEach((indicator, index) => {
        indicator.addEventListener('click', () => {
            currentIndex = index;
            updateCarousel();
        });
    });

    // 自动轮播（可选）
    let autoPlay = setInterval(nextSlide, 5000);

    // 鼠标悬停时暂停自动轮播
    container.addEventListener('mouseenter', () => {
        clearInterval(autoPlay);
    });

    container.addEventListener('mouseleave', () => {
        autoPlay = setInterval(nextSlide, 5000);
    });
}

// 生成星级评分
function generateStars(rating) {
    const fullStars = Math.floor(rating);
    const hasHalfStar = rating % 1 >= 0.5;
    const emptyStars = 5 - fullStars - (hasHalfStar ? 1 : 0);

    return '★'.repeat(fullStars) + (hasHalfStar ? '☆' : '') + '☆'.repeat(emptyStars);
}

// 获取徽章文本
function getBadgeText(shop) {
    if (shop.isCurrentLocation) return '当前位置';
    if (shop.rating >= 4.5) return '人气推荐';
    if (shop.rating >= 4.0) return '网红打卡';
    if (shop.tags && shop.tags.includes('new')) return '新店开业';
    return '推荐';
}

// 获取徽章样式类
function getBadgeClass(shop) {
    if (shop.isCurrentLocation) return 'badge-current';
    if (shop.rating >= 4.5) return 'badge-popular';
    if (shop.rating >= 4.0) return 'badge-hot';
    if (shop.tags && shop.tags.includes('new')) return 'badge-new';
    return 'badge-default';
}

// 查看店铺详情
function viewShopDetail(shopId) {
    console.log('查看店铺详情:', shopId);
    // 这里可以跳转到店铺详情页或打开详情弹窗
    // window.location.href = `/shop/detail/${shopId}`;
}
